'use strict';

function TicTacToeView(jqTable, jqScore) {
	this._jqTable = jqTable;
	this._jqScore = jqScore;
}

TicTacToeView.prototype.init = function(controller) {
	this._controller = controller;
	this._jqSquares = [];

	this._jqTable.empty();
	for (var row = 0; row < 3; row++) {
		var jqRow = $('<tr>');
		this._jqTable.append(jqRow);
		for (var col = 0; col < 3; col++) {
			var jqSquare = $('<td>');
			jqRow.append(jqSquare);
			this._jqSquares.push(jqSquare);

			jqSquare.on('click', createClickHander(row, col));
		}
	}

	var self = this;
	function createClickHander(row, col) {
		return function() {
			self._controller.move(row, col);
		};
	}
};

TicTacToeView.prototype.update = function(board) {
	var squares = board.state();
	for (var i = 0; i < squares.length; i++) {
		this._jqSquares[i].text(squares[i]);
		this._jqSquares[i].addClass('' + squares[i]);
	}
};

TicTacToeView.prototype.onStale = function() {
	setTimeout(function() {
		alert('Stale');
	}, 100);
};

TicTacToeView.prototype.onWinner = function(winner) {
	// setTimeout(function() {
	// alert('Player ' + winner + " has won");
	// }, 100);
};

// TicTacToeView.prototype.onFail = function() {
// setTimeout(function() {
// alert('Fail');
// }, 100);
// };

TicTacToeView.prototype.onSolved = function() {
	setTimeout(function() {
		alert('Solved!');
	}, 100);
};

TicTacToeView.prototype.updateScore = function(match) {
	var matchResults = match.results;
	for (var i = 0; i < matchResults.length; i++) {
		var winner = matchResults[i];
		var row = this._jqScore.find('tr:nth-child(' + (i + 2) + ')');
		var pos = (winner === Player.O) ? 1 : 2;
		row.find('td:nth-child(' + pos + ')').html('&#10004;');
	}
};